<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class CMiniyunActiveDataProvider extends CActiveDataProvider
{
	public $config;	public $data;	public $ids;	public function __construct($config){
		$this->config = $config;
	}

	
	private function _getPagination(){
		$pagination = new CPagination;
				$pageIndex = Yii::app()->request->getParam("page",1)-1;
				$pageCount = $this->getTotalItemCount()/$pagination->pageSize;
		if($this->getTotalItemCount()%$pagination->pageSize>0){
			$pageCount = $pageCount+1;
		}
				if($pageIndex<0) $pageIndex = 0;
		if($pageIndex>$pageCount) $pageIndex = $pageCount;
				$pagination->currentPage=$pageIndex;
		$pagination->itemCount=$this->getTotalItemCount();
		return $pagination;
	}

	
	protected function initData($condition = "", $order="updated_at desc"){
				$filters = $this->config->getFormFilters();
		foreach($filters as $key=>$filterValue){
			$value = Yii::app()->request->getParam($key);
			if(isset($value)){
				if(strlen($condition)>0){					$condition = $condition." and ";
				}
				$condition = $condition." ".$this->model->primaryKey()." in(".str_replace("?",$value,$filterValue["condition"]).")";			}
		}
		$formConditon = $this->config->getSearchKey();
		if(isset($formConditon)){
			if(strlen($condition)>0){				$condition = $condition." and ";
			}
			$condition = $condition." ".$this->model->primaryKey()." in($formConditon)";
		}
				$ids = Yii::app()->request->getParam("id");
		if(strlen($ids)>0){
			if(strlen($condition)>0){				$condition = $condition." and ";
			}
			$condition = $condition." ".$this->model->primaryKey()." in(".$ids.")";
		}
		if($condition!=""){
			$this->setTotalItemCount($this->model->count($condition));
		}else{
			$this->setTotalItemCount($this->model->count());
		}
		$pagination = $this->_getPagination();
		$this->setPagination($pagination);

				if($condition!=""){
			$this->data = $this->model->findAll(array(
			  'condition' =>$condition,
			  'order'     =>$order,
			  'limit'     =>$pagination->pageSize,
			  'offset'    =>$pagination->currentPage*$pagination->pageSize,
			)
			);
		}else{
			$this->data = $this->model->findAll(array(
            'order'     =>$order,
            'limit'     =>$pagination->pageSize,
            'offset'    =>$pagination->currentPage*$pagination->pageSize,
			)
			);
		}
		$this->ids = "";
				foreach($this->data as $index=>$item){
			$id   = isset($item->id)?$item->id: $item->osr_id;
			if(strlen($this->ids)>0){
			 $this->ids = $this->ids.",";
			}
			$this->ids=$this->ids.$id;
		}
	}
}